const express = require("express");
const multer = require("multer");
const router = express.Router();
const db = require("../models");
const verify = require("../tools/verifyToken");
require("dotenv").config();

const config = process.env;

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./uploads");
  },
  filename: function (req, file, cb) {
    console.log(file);
    const uniqueSuffix = Date.now();
    cb(null, uniqueSuffix + "-" + file.fieldname);
  },
});

const upload = multer({ storage: storage });
router.post("/implement", verify, upload.any(), (req, res, next) => {
  // console.log(req.body.id)
  const file = req.files[0];
  db.Implement.update(
    {
      docs: `${config.SERVER}:${config.PORT}/download/${file.filename}`,
      doc_name: file.fieldname,
    },
    {
      where: {
        id: req.body.id,
      },
    }
  )
    .then((result) => {
      res.send({ msg: `${file.fieldname}已经上传成功`, updated: result });
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/contract", verify, upload.any(), (req, res, next) => {
  // console.log(req.body.id)
  const file = req.files[0];
  db.Contract.update(
    {
      appendix: `${config.SERVER}:${config.PORT}/download/${file.filename}`,
      filename: file.fieldname,
    },
    {
      where: {
        id: req.body.id,
      },
    }
  )
    .then((result) => {
      res.send({ msg: `${file.fieldname}已经上传成功`, updated: result });
    })
    .catch((err) => {
      res.send(err);
    });
});

module.exports = router;
